/**
 * @设置
 */
import { HeartTwoTone, SmileTwoTone } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Alert, Card, Typography, Tabs, Form, Row, Col, Input, Button, message, Table, Popconfirm, Modal, Select, } from 'antd';
const { TabPane } = Tabs;
import React, { useRef, useState, useEffect, } from 'react';
import { getUserInformation, setUserInformation, getNurseList, delUserInformation, getDeptList, } from '@/services/ant-design-pro/api';

const Admin: React.FC = () => {
  const intl = useIntl();
  const [form] = Form.useForm();
  const [operateType, setOperateType] = useState("see"); //操作状态 新增|修改
  const [adminVis, setAdminVis] = useState(false); //是否管理员
  const [dataSource, setDataSource] = useState([]); //列表信息
  const [modalVisible, setModalVisibles] = useState(false); //是否管理员
  const [deptList, setDeptList] = useState([]); //部门



  // const [userList, setUserList] = useState({ name: "", username: "", password: "", email: "", });



  useEffect(() => {
    getUserList()
    getDeptListApi()
  }, [])
  // 获取部门
  const getDeptListApi = () => {
    getDeptList({
      username: localStorage.getItem("username") || "",
    }).then((res: any) => {
      setDeptList(res.data)
    })
  }
  // 获取当前用户信息_判断权限
  const getUserList = () => {
    getUserInformation({
      username: localStorage.getItem("username") || "",//
    }).then((res: any) => {
      if (res.data) {
        form.setFieldsValue(res.data);
        setAdminVis(res.data.adminVis) // 是否为管理员
      }
    })
  }
  // 获取售后人员信息列表
  const getNurseListAPI = () => {
    getNurseList({
      username: localStorage.getItem("username") || "",//'用户Id'
    }).then((res: any) => {
      if (res.data) {
        setDataSource(res.data)
      }
    })
  }

  /**
   * @切换Tabs_Change事件
   * @param key 切换时 唯一标识
   */
  const callback = (key: string) => {
    console.log(key, 'key')
    setOperateType("see")
    if (key == "1") {
      getUserList()
    } else if (key == "2") {
      getNurseListAPI()
    }
  }
  /**
   * @编辑_保存
   */
  const onFinish = (val: any) => {
    if (operateType == "see") {
      setOperateType("edit")
    } else if (operateType == "edit" || operateType == "add") {
      // 保存
      console.log(val, 'val')
      setUserInformation(val).then((res: any) => {
        if (res.success) {
          message.success("保存成功！")
          modalVisible && getNurseListAPI()
          setOperateType("see")
          setModalVisibles(false)
        }
      })
    }
  }
  /**
   * @删除用户
   * @param record 删除用户信息
   */
  const deleteUser = (record: any) => {
    if (record.adminVis) {
      message.warning("管理员账号不可删除!")
      return
    }
    if (!record.username) {
      message.warning("当前账号异常!")
      return
    }
    delUserInformation({ username: record.username }).then((res: any) => {
      if (res.success) {
        message.success("删除成功！")
        getNurseListAPI()
      }
    })
  }

  const formItem = () => {
    return <Form
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      layout="horizontal"
      onFinish={onFinish}
      style={{ width: 300 }}
    >
      <Form.Item label="姓名" name="name"
        help={operateType == "add" ? <span style={{ color: '#FFC000' }}>姓名一经新增不可修改</span> : ""}
        rules={[{ required: true, message: '请输入姓名!' }]} >
        <Input placeholder='请输入姓名' disabled={operateType == "add" ? false : true} />
      </Form.Item>
      <Form.Item label="账号" name="username"
        help={operateType == "add" ? <span style={{ color: '#FFC000' }}>账号一经新增不可修改</span> : ""}
        rules={[{ required: true, message: '请输入账号!' }]} >
        <Input placeholder='请输入账号' disabled={operateType == "add" ? false : true} />
      </Form.Item>
      <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码!' }]} >
        <Input placeholder='请输入密码' disabled={(operateType == "add" || operateType == "edit") ? false : true} />
      </Form.Item>
      <Form.Item label="邮箱" name="email">
        <Input placeholder='请输入邮箱' disabled={(operateType == "add" || operateType == "edit") ? false : true} />
      </Form.Item>
      <Form.Item label="部门" name="deptId">
        <Select placeholder='请选择部门' disabled={(operateType == "add" || operateType == "edit") ? false : true} >
          {Array.isArray(deptList) && deptList.map((item: any) => {
            return <Option value={item.deptId}>{item.deptName}</Option>
          })}
        </Select>
      </Form.Item>
      <Form.Item style={{ width: '100%', position: 'relative' }} wrapperCol={{ span: 24 }}>
        <div style={{ position: 'absolute', right: 0 }}>
          {modalVisible && <Button htmlType="submit" style={{ marginRight: 10 }} onClick={() => {
            setModalVisibles(false)
            setOperateType("see")
            form.setFieldsValue({
              "name": "",
              "username": "",
              "password": "",
              "email": "",
              "deptId": "",
              "adminVis": false,
            })
          }}>
            关闭
          </Button>}
          <Button type="primary" htmlType="submit">
            {operateType == "see" ? "编辑" : operateType == "edit" ? "保存" : operateType == "add" ? "新增" : ""}
          </Button>
        </div>
      </Form.Item>
    </Form >
  }

  const columns: any = [{
    title: '姓名',
    dataIndex: 'name',
  }, {
    title: '账号',
    dataIndex: 'username',
  }, {
    title: '密码',
    dataIndex: 'password',
  }, {
    title: '邮箱',
    dataIndex: 'email',
  }, {
    title: '部门',
    dataIndex: 'deptId',
    render: (text: any, record: object) => {
      return (
        <div>
          {Array.isArray(deptList) && deptList.length > 2 && deptList[text - 1]?.deptName}
        </div>
      )
    }
  }, {
    title: '操作',
    dataIndex: '',
    align: 'center',
    render: (text: any, record: object) => (
      <div>
        <Button type="primary" onClick={() => {
          setModalVisibles(true)
          setOperateType("edit")
          form.setFieldsValue(record)
        }}>编辑</Button>
        <Popconfirm
          title="确认删除该账号?"
          onConfirm={() => deleteUser(record)}
          okText="确认"
          cancelText="取消"
        >
          <Button style={{ backgroundColor: 'red', color: 'white', borderColor: 'red', marginLeft: 10 }}>删除</Button>
        </Popconfirm>
      </div>
    )

  },]
  return (
    <Tabs defaultActiveKey="1" onChange={callback} tabBarExtraContent={adminVis ? <Button type="primary" onClick={() => {
      setModalVisibles(true)
      setOperateType("add")
      form.setFieldsValue({
        "name": "",
        "username": "",
        "password": "",
        "email": "",
        "deptId": "",
        "adminVis": false,
      })
    }}>新增售后人员</Button> : <></>}>
      <TabPane tab="个人信息管理" key="1">
        {formItem()}
      </TabPane>
      {adminVis && <TabPane tab="售后人员信息列表" key="2">
        <Table dataSource={dataSource} columns={columns} />
        <Modal
          title={`${operateType == "edit" ? "编辑" : operateType == "add" ? "新增" : ""}账号信息`}
          visible={modalVisible}
          // onOk={handleOk}
          onCancel={() => { setModalVisibles(false) }}
          footer={null}
          // style={{ width: 350 }}
          width={370}
        >
          <div style={{ marginTop: 30 }}>
            {formItem()}
          </div>
        </Modal>
      </TabPane>}
    </Tabs>
  );
};

export default Admin;
